import React, { useState, useRef, useEffect } from 'react';

// 辅助函数：将 snake_case 转换为 camelCase (蛇形命名转换为驼峰命名)
const snakeToCamel = (s) => {
    return s.replace(/([-_][a-z])/ig, ($1) => {
        return $1.toUpperCase()
            .replace('-', '')
            .replace('_', '');
    });
};

// 辅助函数：将字符串的首字母大写
const capitalizeFirstLetter = (string) => {
    return string.charAt(0).toUpperCase() + string.slice(1);
};

// 主要应用组件
const App = () => {
    const [jsonInput, setJsonInput] = useState('');
    const [modelName, setModelName] = useState('RootModel'); // 根模型名称，默认 RootModel
    // 新增：类名前缀状态
    const [classNamePrefix, setClassNamePrefix] = useState(''); 
    const [objcHeader, setObjcHeader] = useState('');
    const [objcImplementation, setObjcImplementation] = useState('');
    const [swiftCode, setSwiftCode] = useState('');
    const [flutterCode, setFlutterCode] = useState(''); // 新增 Flutter 代码状态
    const [error, setError] = useState('');
    const [isLoading, setIsLoading] = useState(false);
    const [suggestedModelName, setSuggestedModelName] = useState('');
    const [isSuggestingName, setIsSuggestingName] = useState(false);
    const [modelExplanation, setModelExplanation] = useState('');
    const [isExplainingModel, setIsExplainingModel] = useState(false);
    // 语言选择状态：'both'（全部）, 'objc'（Objective-C）, 'swift'（Swift）, 'flutter'（Flutter）
    const [selectedLanguage, setSelectedLanguage] = useState('both');
    // Swift 框架选择状态，默认为 Codable
    const [swiftFramework, setSwiftFramework] = useState('Codable');
    // Objective-C 框架选择状态，默认为 System
    const [objcFramework, setObjcFramework] = useState('System');
    // Flutter 框架选择状态，默认为 System
    const [flutterFramework, setFlutterFramework] = useState('System');


    const objcHeaderRef = useRef(null);
    const objcImplementationRef = useRef(null);
    const swiftCodeRef = useRef(null);
    const flutterCodeRef = useRef(null); // 新增 Flutter 代码引用

    // Gemini API 密钥 - Canvas 环境将自动注入，此处留空即可
    const apiKey = "AIzaSyCvKgb0Vj51EbpIrWlY9vMqnZAk_oFsXr0";

    // 处理 JSON 解析和模型生成的功能
    const generateModels = () => {
        setError('');
        // 清除所有之前的输出
        setObjcHeader('');
        setObjcImplementation('');
        setSwiftCode('');
        setFlutterCode(''); // 清除 Flutter 代码
        setSuggestedModelName(''); // 清除之前的建议名称
        setModelExplanation(''); // 清除之前的模型解释
        setIsLoading(true);

        try {
            const parsedData = JSON.parse(jsonInput);
            let rootDataForModel = parsedData;

            // 检查根 JSON 是否包含 'code', 'msg', 'data' 结构
            // 如果存在且 'data' 是一个对象，则提取 'data' 作为模型生成的数据源
            if (parsedData && typeof parsedData === 'object' && parsedData.hasOwnProperty('data') &&
                typeof parsedData.data === 'object' && parsedData.data !== null) {
                rootDataForModel = parsedData.data;
            }

            const generatedOCModels = {};
            const generatedSwiftModels = {};
            const generatedFlutterModels = {}; // 存储生成的 Flutter 模型

            // 追踪已处理的模型名称，避免无限递归或重复定义
            const processedModelNames = new Set();

            // 用于 Swift 和 Flutter 的全局导入
            const swiftGlobalImports = new Set(['import Foundation']); // Foundation 是默认导入
            const flutterGlobalImports = new Set();
            const flutterPartDeclarations = new Set();

            // 辅助函数：判断是否是 ISO 8601 日期字符串
            const isISO8601Date = (str) => {
                // 简单的 ISO 8601 日期时间正则，更严格的需要更复杂的正则
                return /^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}:\d{2}(Z|[\+\-]\d{2}(:?\d{2})?)?)?$/.test(str);
            };


            // 递归函数：处理 JSON 并构建模型
            const processObject = (obj, currentModelName) => {
                // 如果模型已处理，则直接返回，避免重复处理
                if (processedModelNames.has(currentModelName)) {
                    return;
                }
                processedModelNames.add(currentModelName);


                const objcProperties = [];
                const objcSynthesize = [];
                const objcInitAssignments = [];
                const objcCustomPropertyMappers = []; // 用于 MJExtension/YYModel 的属性映射
                const objcContainerPropertyGenericClasses = []; // 用于 MJExtension/YYModel 的容器属性泛型类映射

                const swiftProperties = [];
                let swiftProtocolConformance = ': Codable'; // 默认遵循 Codable
                let swiftClassOrStructDeclaration = 'struct'; // 默认声明为 struct
                let swiftInitializerBody = ''; // 自定义初始化器的内容
                const swiftCodingKeys = [];

                const flutterProperties = [];
                const flutterConstructorParams = [];
                const flutterFromJsonLines = [];
                const flutterToJsonLines = [];


                if (swiftFramework === 'HandyJSON') {
                    swiftGlobalImports.add('import HandyJSON'); // 添加到全局导入
                    swiftGlobalImports.add('import UIKit'); // HandyJSON 示例通常包含 UIKit
                    swiftProtocolConformance = ': HandyJSON';
                    swiftClassOrStructDeclaration = 'class'; // HandyJSON 通常使用 class
                    swiftInitializerBody = `\n    required init() {}\n`;
                } else if (swiftFramework === 'SwiftyJSON') {
                    swiftGlobalImports.add('import SwiftyJSON'); // 添加到全局导入
                    swiftProtocolConformance = ''; // SwiftyJSON 模型不需要遵循特定的协议进行映射
                    swiftClassOrStructDeclaration = 'class'; // SwiftyJSON 解析时通常使用 class
                    swiftInitializerBody = `\n    init(_ json: JSON) {\n`;
                }

                // 使用提供的对象作为属性源
                const currentPropertiesObj = obj;

                for (const key in currentPropertiesObj) {
                    if (currentPropertiesObj.hasOwnProperty(key)) {
                        const value = currentPropertiesObj[key]; // 当前属性的值
                        const camelKey = snakeToCamel(key); // 将 snake_case 转换为 camelCase

                        // 确定 Swift 类型和默认值/可选性
                        let swiftPropertyType;
                        let swiftPropertySuffix = ''; // 用于 HandyJSON 的默认值或 !
                        let isCodableOptional = false; // 用于 Codable 的 '?'

                        if (typeof value === 'string') {
                            if (isISO8601Date(value)) {
                                swiftPropertyType = 'Date';
                                isCodableOptional = true; // 日期通常是可选的
                                if (swiftFramework === 'HandyJSON') swiftPropertySuffix = ' = nil';
                                else if (swiftFramework === 'SwiftyJSON') swiftInitializerBody += `        self.${camelKey} = json["${key}"].string.flatMap { DateFormatter.iso8601.date(from: $0) }\n`;
                            } else if (!isNaN(parseInt(value)) && String(parseInt(value)) === value) { // 检查是否是纯整数字符串
                                const parsedIntValue = parseInt(value);
                                const MAX_INT32 = 2147483647; // 2^31 - 1
                                // 根据数值大小推断 Int 或 Int64
                                if (parsedIntValue > MAX_INT32 || parsedIntValue < -MAX_INT32) {
                                    swiftPropertyType = 'Int64';
                                } else {
                                    swiftPropertyType = 'Int';
                                }
                                if (swiftFramework === 'HandyJSON') swiftPropertySuffix = ` = ${swiftPropertyType.includes('Int') ? '0' : '0.0'}`;
                                else if (swiftFramework === 'Codable') isCodableOptional = true;
                                else if (swiftFramework === 'SwiftyJSON') swiftInitializerBody += `        self.${camelKey} = json["${key}"].intValue\n`;
                            } else if (!isNaN(parseFloat(value)) && isFinite(value)) { // 检查是否是浮点数字符串
                                swiftPropertyType = 'Double';
                                if (swiftFramework === 'HandyJSON') swiftPropertySuffix = ' = 0.0';
                                else if (swiftFramework === 'Codable') isCodableOptional = true;
                                else if (swiftFramework === 'SwiftyJSON') swiftInitializerBody += `        self.${camelKey} = json["${key}"].doubleValue\n`;
                            } else if (value.toLowerCase() === 'true' || value.toLowerCase() === 'false') {
                                swiftPropertyType = 'Bool';
                                if (swiftFramework === 'HandyJSON') swiftPropertySuffix = ' = false';
                                else if (swiftFramework === 'Codable') isCodableOptional = true;
                                else if (swiftFramework === 'SwiftyJSON') swiftInitializerBody += `        self.${camelKey} = json["${key}"].boolValue\n`;
                            } else { // 如果其他解析失败，默认为 String
                                swiftPropertyType = 'String';
                                if (swiftFramework === 'HandyJSON') swiftPropertySuffix = ' = ""';
                                else if (swiftFramework === 'Codable') isCodableOptional = true;
                                else if (swiftFramework === 'SwiftyJSON') swiftInitializerBody += `        self.${camelKey} = json["${key}"].stringValue\n`;
                            }
                        } else if (typeof value === 'number') {
                            if (Number.isInteger(value)) {
                                const MAX_INT32 = 2147483647; // 2^31 - 1
                                if (value > MAX_INT32 || value < -MAX_INT32) {
                                    swiftPropertyType = 'Int64';
                                } else {
                                    swiftPropertyType = 'Int';
                                }
                                if (swiftFramework === 'HandyJSON') swiftPropertySuffix = ` = ${swiftPropertyType.includes('Int') ? '0' : '0.0'}`;
                                else if (swiftFramework === 'Codable') isCodableOptional = true;
                                else if (swiftFramework === 'SwiftyJSON') swiftInitializerBody += `        self.${camelKey} = json["${key}"].intValue\n`;
                            } else { // 浮点数
                                swiftPropertyType = 'Double';
                                if (swiftFramework === 'HandyJSON') swiftPropertySuffix = ' = 0.0';
                                else if (swiftFramework === 'Codable') isCodableOptional = true;
                                else if (swiftFramework === 'SwiftyJSON') swiftInitializerBody += `        self.${camelKey} = json["${key}"].doubleValue\n`;
                            }
                        } else if (typeof value === 'boolean') {
                            swiftPropertyType = 'Bool';
                            if (swiftFramework === 'HandyJSON') {
                                if (key === "signIn" && currentModelName === modelName) { // signIn 在示例中是 Bool!
                                    swiftPropertySuffix = '!';
                                } else {
                                    swiftPropertySuffix = ' = false';
                                }
                            } else if (swiftFramework === 'Codable') isCodableOptional = true;
                            else if (swiftFramework === 'SwiftyJSON') swiftInitializerBody += `        self.${camelKey} = json["${key}"].boolValue\n`;
                        } else if (Array.isArray(value)) {
                            let arrayElementType = 'Any';
                            if (value.length > 0) {
                                const firstElementType = value[0];
                                if (typeof firstElementType === 'object' && firstElementType !== null) {
                                    // FIXED: 移除嵌套模型名称中的下划线
                                    let nestedModelName = `${currentModelName}${capitalizeFirstLetter(camelKey)}`; 
                                    processObject(firstElementType, nestedModelName); // 递归处理
                                    arrayElementType = nestedModelName;
                                } else {
                                    // 原始类型数组
                                    if (typeof firstElementType === 'string') {
                                        arrayElementType = isISO8601Date(firstElementType) ? 'Date' : 'String';
                                    } else if (typeof firstElementType === 'number') {
                                        arrayElementType = Number.isInteger(firstElementType) ? 'Int' : 'Double';
                                    } else if (typeof firstElementType === 'boolean') {
                                        arrayElementType = 'Bool';
                                    } else {
                                        arrayElementType = 'Any'; // fallback for other types
                                    }
                                }
                            }
                            swiftPropertyType = `[${arrayElementType}]`;
                            if (swiftFramework === 'HandyJSON') swiftPropertySuffix = ' = []';
                            else if (swiftFramework === 'Codable') isCodableOptional = true;
                            else if (swiftFramework === 'SwiftyJSON') {
                                if (arrayElementType.includes('Model') || arrayElementType === 'Date') { // 对象数组或日期数组
                                    swiftInitializerBody += `        self.${camelKey} = json["${key}"].arrayValue.compactMap { ${arrayElementType}(json: $0) }\n`; // 使用 compactMap 处理可选初始化
                                } else { // 原始类型数组
                                    swiftInitializerBody += `        self.${camelKey} = json["${key}"].arrayObject as? [${arrayElementType}] ?? []\n`;
                                }
                            }
                        } else if (typeof value === 'object' && value !== null) {
                            // FIXED: 移除嵌套模型名称中的下划线
                            let nestedModelName = `${currentModelName}${capitalizeFirstLetter(camelKey)}`; 
                            processObject(value, nestedModelName); // 递归处理
                            swiftPropertyType = nestedModelName;
                            if (swiftFramework === 'HandyJSON') swiftPropertySuffix = '!'; // HandyJSON 中对象通常为隐式解包可选
                            else if (swiftFramework === 'Codable') isCodableOptional = true;
                            else if (swiftFramework === 'SwiftyJSON') swiftInitializerBody += `        self.${camelKey} = ${nestedModelName}(json: json["${key}"])\n`;
                        } else if (value === null) {
                            // 对 null 值的更智能推断，默认为 String? 而不是 Any?
                            swiftPropertyType = 'String'; // 默认为 String
                            isCodableOptional = true; // 总是可选的
                            if (swiftFramework === 'HandyJSON') swiftPropertySuffix = ' = nil';
                            else if (swiftFramework === 'SwiftyJSON') swiftInitializerBody += `        self.${camelKey} = json["${key}"].string\n`; // SwiftyJSON 属性仍为 string
                        }

                        // 添加属性声明行 (使用 var)
                        let propDeclaration = `    var ${camelKey}: ${swiftPropertyType}`;
                        if (swiftFramework === 'Codable') {
                            propDeclaration += isCodableOptional ? '?' : '';
                        } else if (swiftFramework === 'HandyJSON') {
                            propDeclaration += swiftPropertySuffix; // 将是 = "" 或 ! 或 = nil
                        } else if (swiftFramework === 'SwiftyJSON') {
                            propDeclaration += '?'; // SwiftyJSON 属性通常是可选的，以便优雅地处理缺失的键
                        }
                        swiftProperties.push(propDeclaration);

                        // 如果原始键与驼峰命名键不同，则为 Codable 添加 CodingKey
                        if (swiftFramework === 'Codable' && camelKey !== key) {
                            swiftCodingKeys.push(`        case ${camelKey} = "${key}"`);
                        }

                        // Objective-C 属性推断和映射
                        let objcType = 'id'; // 默认为通用 id
                        let finalObjcPropertyName = camelKey; // 默认属性名为驼峰命名
                        let objcPropertyAttributes = '(nonatomic, strong)'; // 默认属性修饰符

                        // 常见的 Objective-C 关键字和可能冲突的属性名
                        const problematicObjcKeywords = new Set([
                            'id', 'new', 'description', 'class', 'hash', 'init', 'alloc', 'copy', 'mutableCopy',
                            'retain', 'release', 'autorelease', 'dealloc', 'self', 'super',
                            'private', 'protected', 'public', 'readwrite', 'readonly', 'assign',
                            'strong', 'weak', 'copy', 'atomic', 'nonatomic'
                        ]);

                        // 属性映射逻辑：如果原始键与驼峰命名键不同，或者驼峰命名键是 OC 关键字
                        if (key !== camelKey || problematicObjcKeywords.has(camelKey) || problematicObjcKeywords.has(key)) {
                            if (key === "id") { // 特殊处理 "id" 键
                                finalObjcPropertyName = "objId"; // 映射到一个更安全的名称
                                if (objcFramework === 'MJExtension' || objcFramework === 'YYModel') {
                                    objcCustomPropertyMappers.push(`        @\"${finalObjcPropertyName}\" : @\"${key}\",`);
                                }
                            } else if (problematicObjcKeywords.has(camelKey)) {
                                // 如果驼峰命名属性名是 OC 关键字，则添加下划线前缀
                                finalObjcPropertyName = `_${camelKey}`;
                                if (objcFramework === 'MJExtension' || objcFramework === 'YYModel') {
                                    objcCustomPropertyMappers.push(`        @\"${finalObjcPropertyName}\" : @\"${key}\",`);
                                }
                            } else if (key !== camelKey) {
                                // 正常的驼峰命名转换，且 camelKey 不是关键字，则添加映射
                                if (objcFramework === 'MJExtension' || objcFramework === 'YYModel') {
                                    objcCustomPropertyMappers.push(`        @\"${camelKey}\" : @\"${key}\",`);
                                }
                            }
                        }

                        // Objective-C 类型推断细化
                        if (typeof value === 'string') {
                            const parsedIntValue = parseInt(value);
                            const parsedFloatValue = parseFloat(value);

                            if (!isNaN(parsedIntValue) && String(parsedIntValue) === value) {
                                objcType = 'NSNumber *'; // 数值字符串解析为 NSNumber
                                objcPropertyAttributes = '(nonatomic, strong)';
                            } else if (!isNaN(parsedFloatValue) && isFinite(value)) {
                                objcType = 'NSNumber *'; // 浮点数字符串解析为 NSNumber
                                objcPropertyAttributes = '(nonatomic, strong)';
                            } else if (value.toLowerCase() === 'true' || value.toLowerCase() === 'false') {
                                objcType = 'NSNumber *'; // 布尔字符串解析为 NSNumber (使用 boolValue)
                                objcPropertyAttributes = '(nonatomic, strong)';
                            } else {
                                objcType = 'NSString *';
                                objcPropertyAttributes = '(nonatomic, copy)'; // 字符串使用 copy
                            }
                        } else if (typeof value === 'number') {
                            objcType = 'NSNumber *'; // 所有数字类型都包装为 NSNumber
                            objcPropertyAttributes = '(nonatomic, strong)';
                        } else if (typeof value === 'boolean') {
                            objcType = 'NSNumber *'; // 布尔类型包装为 NSNumber (使用 @(YES/NO) 或 NSNumber numberWithBool:)
                            objcPropertyAttributes = '(nonatomic, strong)';
                        } else if (Array.isArray(value)) {
                            let inferredArrayElementType = 'id';
                            if (value.length > 0) {
                                const firstElementType = value[0];
                                if (typeof firstElementType === 'object' && firstElementType !== null) {
                                    // FIXED: 移除嵌套模型名称中的下划线
                                    let nestedModelNameOC = `${currentModelName}${capitalizeFirstLetter(camelKey)}`;
                                    processObject(firstElementType, nestedModelNameOC); // 递归调用
                                    objcType = `NSArray<${nestedModelNameOC} *> *`;
                                    // 为 MJExtension/YYModel 添加泛型类映射
                                    if (objcFramework === 'MJExtension') {
                                        objcContainerPropertyGenericClasses.push(`        @\"${finalObjcPropertyName}\" : [${nestedModelNameOC} class],`);
                                    } else if (objcFramework === 'YYModel') {
                                        objcContainerPropertyGenericClasses.push(`        @\"${finalObjcPropertyName}\" : [${nestedModelNameOC} class],`);
                                    }
                                } else {
                                    // 原始类型数组，从第一个元素推断类型
                                    if (typeof firstElementType === 'string') inferredArrayElementType = 'NSString *';
                                    else if (typeof firstElementType === 'number') inferredArrayElementType = 'NSNumber *';
                                    else if (typeof firstElementType === 'boolean') inferredArrayElementType = 'NSNumber *';
                                    objcType = `NSArray<${inferredArrayElementType}> *`;
                                }
                            } else {
                                objcType = 'NSArray *'; // 空数组，通用类型
                            }
                            objcPropertyAttributes = '(nonatomic, copy)'; // 数组使用 copy
                        } else if (typeof value === 'object' && value !== null) {
                            // FIXED: 移除嵌套模型名称中的下划线
                            let nestedModelNameOC = `${currentModelName}${capitalizeFirstLetter(camelKey)}`; 
                            processObject(value, nestedModelNameOC); // 递归调用
                            objcType = `${nestedModelNameOC} *`;
                            objcPropertyAttributes = '(nonatomic, strong)'; // 对象使用 strong
                        } else if (value === null) {
                            // 对 null 值的更智能推断，默认为 NSString * 而不是 id
                            objcType = 'NSString *'; // 默认为 NSString *
                            objcPropertyAttributes = '(nonatomic, strong, nullable)'; // 明确标记为 nullable
                        }

                        // 还原为用户在以前版本中看到的标准代码样式：`@property (nonatomic, assign) NSInteger rowCount;`
                        objcProperties.push(`@property ${objcPropertyAttributes} ${objcType}${objcType.endsWith('*') ? '' : ' '}${finalObjcPropertyName};`);

                        // MJExtension/YYModel 不需要 @synthesize
                        if (objcFramework === 'System') {
                            objcSynthesize.push(`@synthesize ${finalObjcPropertyName} = _${finalObjcPropertyName};`);
                            let objCInitAssignment = `        _${finalObjcPropertyName} = dictionary[@"${key}"];`;
                            if (objcType.includes('*') && objcType !== 'NSString *' && !objcType.includes('NSArray') && !objcType.includes('id') && objcPropertyAttributes.includes('nullable')) {
                                // 是自定义对象，且可能为 nil
                                objCInitAssignment = `        if ([dictionary[@"${key}"] isKindOfClass:[NSDictionary class]]) {\n            _${finalObjcPropertyName} = [[${objcType.replace(' *', '')} alloc] initWithDictionary:dictionary[@"${key}"]];\n        }`;
                            } else if (objcType === 'NSNumber *') {
                                objCInitAssignment = `        _${finalObjcPropertyName} = [dictionary[@"${key}"] isKindOfClass:[NSNumber class]] ? dictionary[@"${key}"] : nil;`;
                                if (isISO8601Date(value)) { // 对日期字符串进行特殊处理，转换为 NSDate
                                    objCInitAssignment = `        if ([dictionary[@"${key}"] isKindOfClass:[NSString class]]) {\n            NSDateFormatter *formatter = [[NSDateFormatter alloc] init];\n            formatter.dateFormat = @\"yyyy-MM-dd'T'HH:mm:ssZ\"; // 假设 ISO 8601 格式\n            _${finalObjcPropertyName} = [formatter dateFromString:dictionary[@"${key}"]];\n        }`;
                                    objcType = 'NSDate *';
                                    objcPropertyAttributes = '(nonatomic, strong)';
                                    objcProperties[objcProperties.length - 1] = `@property ${objcPropertyAttributes} ${objcType}${objcType.endsWith('*') ? '' : ' '}${finalObjcPropertyName};`; // 更新属性声明
                                }
                            } else if (objcType === 'NSString *') {
                                objCInitAssignment = `        _${finalObjcPropertyName} = [dictionary[@"${key}"] isKindOfClass:[NSString class]] ? dictionary[@"${key}"] : nil;`;
                            }
                            objcInitAssignments.push(objCInitAssignment);
                        }
                        
                        // Flutter 属性声明和映射
                        let flutterPropertyType = 'dynamic'; // 默认为 dynamic
                        let flutterFromJsonCast = ''; // 用于 fromJson 类型转换
                        let flutterToJsonMapping = `this.${camelKey}`; // toJson 的默认值

                        if (typeof value === 'string') {
                            if (isISO8601Date(value)) {
                                flutterPropertyType = 'DateTime';
                                flutterFromJsonCast = `DateTime.tryParse(json['${key}'] as String)`;
                                flutterGlobalImports.add('import \'package:intl/intl.dart\';'); // 日期格式化可能需要
                            } else {
                                flutterPropertyType = 'String';
                                flutterFromJsonCast = `json['${key}'] as String?`;
                            }
                        } else if (typeof value === 'number') {
                            if (Number.isInteger(value)) {
                                flutterPropertyType = 'int';
                                flutterFromJsonCast = `json['${key}'] as int?`;
                            } else {
                                flutterPropertyType = 'double';
                                flutterFromJsonCast = `json['${key}'] as double?`;
                            }
                        } else if (typeof value === 'boolean') {
                            flutterPropertyType = 'bool';
                            flutterFromJsonCast = `json['${key}'] as bool?`;
                        } else if (Array.isArray(value)) {
                            let arrayElementType = 'dynamic';
                            if (value.length > 0) {
                                const firstElementType = value[0];
                                if (typeof firstElementType === 'object' && firstElementType !== null) {
                                    // FIXED: 移除嵌套模型名称中的下划线
                                    let nestedModelNameFlutter = `${currentModelName}${capitalizeFirstLetter(camelKey)}`;
                                    processObject(firstElementType, nestedModelNameFlutter); // 递归调用
                                    arrayElementType = nestedModelNameFlutter;
                                } else {
                                    if (typeof firstElementType === 'string') {
                                        arrayElementType = isISO8601Date(firstElementType) ? 'DateTime' : 'String';
                                    } else if (typeof firstElementType === 'number') {
                                        arrayElementType = Number.isInteger(firstElementType) ? 'int' : 'double';
                                    } else if (typeof firstElementType === 'boolean') {
                                        arrayElementType = 'bool';
                                    } else {
                                        arrayElementType = 'dynamic'; // fallback
                                    }
                                }
                            }
                            flutterPropertyType = `List<${arrayElementType}>`;
                            if (flutterFramework === 'System') {
                                if (arrayElementType.includes('Model') || arrayElementType === 'DateTime') { // 如果是嵌套的自定义对象列表或日期列表
                                    flutterFromJsonCast = `(json['${key}'] as List<dynamic>?)?.map((e) => ${arrayElementType}.fromJson(e as Map<String, dynamic>)).toList()`;
                                    flutterToJsonMapping = `this.${camelKey}?.map((e) => e.toJson()).toList()`;
                                } else if (arrayElementType === 'DateTime') {
                                    flutterFromJsonCast = `(json['${key}'] as List<dynamic>?)?.map((e) => DateTime.tryParse(e as String)).toList();`;
                                    flutterToJsonMapping = `this.${camelKey}?.map((e) => e?.toIso8601String()).toList();`;
                                } else { // 原始类型列表
                                    flutterFromJsonCast = `(json['${key}'] as List<dynamic>?)?.cast<${arrayElementType}>().toList();`;
                                }
                            }
                        } else if (typeof value === 'object' && value !== null) {
                            // FIXED: 移除嵌套模型名称中的下划线
                            let nestedModelNameFlutter = `${currentModelName}${capitalizeFirstLetter(camelKey)}`;
                            processObject(value, nestedModelNameFlutter); // 递归调用
                            flutterPropertyType = nestedModelNameFlutter;
                            if (flutterFramework === 'System') {
                                flutterFromJsonCast = `json['${key}'] == null ? null : ${nestedModelNameFlutter}.fromJson(json['${key}'] as Map<String, dynamic>)`;
                                flutterToJsonMapping = `this.${camelKey}?.toJson()`;
                            }
                        } else if (value === null) {
                            // 对 null 值的更智能推断，默认为 String? 而不是 dynamic
                            flutterPropertyType = 'String'; // 默认为 String
                            flutterFromJsonCast = `json['${key}'] as String?`;
                        }

                        // Flutter 属性声明
                        if (flutterFramework === 'JsonSerializable') {
                            // 如果 keyName 与 camelKey 不同，或者是问题键，则添加 @JsonKey
                            if (key !== camelKey) {
                                flutterProperties.push(`  @JsonKey(name: '${key}')`);
                            }
                            flutterProperties.push(`  final ${flutterPropertyType}? ${camelKey};`); // JsonSerializable 通常使用 final
                        } else { // System
                            flutterProperties.push(`  ${flutterPropertyType}? ${camelKey};`);
                        }
                        flutterConstructorParams.push(`this.${camelKey}`);

                        // For System fromJson/toJson
                        if (flutterFramework === 'System') {
                            flutterFromJsonLines.push(`    ${camelKey}: ${flutterFromJsonCast},`);
                            flutterToJsonLines.push(`      '${key}': ${flutterToJsonMapping},`);
                        }
                    }
                } // 结束 for 循环

                // 如果 SwiftyJSON 初始化器已打开，则关闭它
                if (swiftFramework === 'SwiftyJSON' && swiftInitializerBody.startsWith('\n    init')) {
                    swiftInitializerBody += `    }\n`;
                }

                // 生成 Objective-C 接口和实现块内容，不包含局部导入
                if (selectedLanguage === 'objc' || selectedLanguage === 'both') {
                    let objcModelMethods = '';
                    let objcInitMethod = '';
                    let objcSynthesizeBlock = '';

                    // For MJExtension/YYModel 方法
                    if (objcFramework === 'MJExtension') {
                        if (objcCustomPropertyMappers.length > 0) {
                            objcModelMethods += `\n+ (NSDictionary *)mj_replacedKeyFromPropertyName {\n    return @{\n${objcCustomPropertyMappers.join('\n')}\n    };\n}\n`;
                        }
                        if (objcContainerPropertyGenericClasses.length > 0) {
                            objcModelMethods += `\n+ (NSDictionary *)mj_objectClassInArray {\n    return @{\n${objcContainerPropertyGenericClasses.join('\n')}\n};\n}\n`;
                        }
                    } else if (objcFramework === 'YYModel') {
                        if (objcCustomPropertyMappers.length > 0) {
                            objcModelMethods += `\n+ (NSDictionary *)modelCustomPropertyMapper {\n    return @{\n${objcCustomPropertyMappers.join('\n')}\n};\n}\n`;
                        }
                        if (objcContainerPropertyGenericClasses.length > 0) {
                            objcModelMethods += `\n+ (NSDictionary *)modelContainerPropertyGenericClass {\n    return @{\n${objcContainerPropertyGenericClasses.join('\n')}\n};\n}\n`;
                        }
                    } else { // System
                        objcInitMethod = `
- (instancetype)initWithDictionary:(NSDictionary *)dictionary {
    self = [super init];
    if (self) {
${objcInitAssignments.join('\n')}
        // 注意：对于嵌套对象和对象数组，如果不使用 MJExtension/YYModel 等库，
        // 您可能需要在此处实现更具体的转换逻辑。
    }
    return self;
}`;
                        objcSynthesizeBlock = objcSynthesize.join('\n');
                    }

                    // 仅存储接口/实现块，不包含导入
                    generatedOCModels[currentModelName] = {
                        header: `
@interface ${currentModelName} : NSObject
${objcProperties.join('\n')}

${objcFramework === 'System' ? '- (instancetype)initWithDictionary:(NSDictionary *)dictionary;' : ''}

@end
`.trim(),
                        implementation: `
@implementation ${currentModelName}
${objcSynthesizeBlock}
${objcInitMethod}
${objcModelMethods}

@end
`.trim()
                    };
                }

                // 根据框架生成 Swift 结构体/类
                if (selectedLanguage === 'swift' || selectedLanguage === 'both') {
                    let codingKeysBlock = '';
                    if (swiftFramework === 'Codable' && swiftCodingKeys.length > 0) {
                        codingKeysBlock = `\n    enum CodingKeys: String, CodingKey {\n${swiftCodingKeys.join('\n')}\n    }`;
                    }

                    // Swift 模型内容，此处不包含导入。导入将在全局添加。
                    generatedSwiftModels[currentModelName] = `
${swiftClassOrStructDeclaration} ${currentModelName} ${swiftProtocolConformance} {
${swiftProperties.join('\n')}
${swiftInitializerBody}
${codingKeysBlock}
}
`;
                }

                // 生成 Flutter/Dart 类
                if (selectedLanguage === 'flutter' || selectedLanguage === 'both') {
                    let classContent = '';
                    if (flutterFramework === 'JsonSerializable') {
                        classContent = `
@JsonSerializable()
class ${currentModelName} {
${flutterProperties.join('\n')}

  ${currentModelName}({${flutterConstructorParams.join(', ')}});

  factory ${currentModelName}.fromJson(Map<String, dynamic> json) => _$${currentModelName}FromJson(json);
  Map<String, dynamic> toJson() => _$${currentModelName}ToJson(this);
}
`;
                        // 对于 json_serializable，全局添加一次 part 文件指令
                        flutterPartDeclarations.add(`part '${modelName.toLowerCase()}_model.g.dart';`);

                    } else { // System
                        classContent = `
class ${currentModelName} {
${flutterProperties.join('\n')}

  ${currentModelName}({${flutterConstructorParams.join(', ')}});

  factory ${currentModelName}.fromJson(Map<String, dynamic> json) {
    return ${currentModelName}(
${flutterFromJsonLines.join('\n')}
    );
  }

  Map<String, dynamic> toJson() {
    return <String, dynamic>{
${flutterToJsonLines.join('\n')}
    };
  }
}
`;
                    }
                    generatedFlutterModels[currentModelName] = { content: classContent };
                }
            }; // 结束 processObject 函数

            // FIXED: 在调用 processObject 之前，处理根模型名称，使其包含前缀
            const actualRootModelName = classNamePrefix + modelName;
            processObject(rootDataForModel, actualRootModelName);

            // 组装所有生成的模型以供显示
            let finalObjcHeader = '';
            let finalObjcImplementation = '';
            let finalSwiftCode = '';
            let finalFlutterCode = '';

            // 收集全局 Objective-C 导入
            const globalObjcHeaderImportsSet = new Set();
            const globalObjcImplementationImportsSet = new Set(); // 只包含主模型头文件

            if (selectedLanguage === 'objc' || selectedLanguage === 'both') {
                globalObjcHeaderImportsSet.add('#import <Foundation/Foundation.h>');
                if (objcFramework === 'MJExtension') {
                    globalObjcHeaderImportsSet.add('#import <MJExtension/MJExtension.h>');
                } else if (objcFramework === 'YYModel') {
                    globalObjcHeaderImportsSet.add('#import <YYModel/YYModel.h>');
                }
                // 在 .m 文件中只导入主模型的头文件；第三方库导入通过 .h 传递
                // FIXED: 导入主模型的头文件时使用实际的根模型名称
                globalObjcImplementationImportsSet.add(`#import "${actualRootModelName}.h"`);
            }

            // 对模型名称进行排序，以保持输出顺序一致
            const sortedOcModelNames = Object.keys(generatedOCModels).sort();

            // 组装 Objective-C 头文件内容
            let objcHeaderContentBlocks = [];
            sortedOcModelNames.forEach(name => {
                objcHeaderContentBlocks.push(generatedOCModels[name].header);
            });
            finalObjcHeader = Array.from(globalObjcHeaderImportsSet).join('\n') + '\n\n' + objcHeaderContentBlocks.join('\n\n');

            // 组装 Objective-C 实现文件内容
            let objcImplementationContentBlocks = [];
            sortedOcModelNames.forEach(name => {
                objcImplementationContentBlocks.push(generatedOCModels[name].implementation);
            });
            finalObjcImplementation = Array.from(globalObjcImplementationImportsSet).join('\n') + '\n\n' + objcImplementationContentBlocks.join('\n\n');


            // 组装 Swift 内容
            const sortedSwiftModelNames = Object.keys(generatedSwiftModels).sort();
            let swiftContentBlocks = [];
            sortedSwiftModelNames.forEach(name => {
                swiftContentBlocks.push(`// MARK: - ${name}.swift\n\n${generatedSwiftModels[name]}`);
            });
            finalSwiftCode = Array.from(swiftGlobalImports).join('\n') + '\n\n' + swiftContentBlocks.join('\n\n');


            // 组装 Flutter 内容
            if (selectedLanguage === 'flutter' || selectedLanguage === 'both') {
                flutterGlobalImports.add('import \'dart:convert\';');
                if (flutterFramework === 'JsonSerializable') {
                    flutterGlobalImports.add('import \'package:json_annotation/json_annotation.dart\';');
                    // flutterPartDeclarations 已经在 processObject 中添加
                }

                const sortedFlutterModelNames = Object.keys(generatedFlutterModels).sort();

                finalFlutterCode += Array.from(flutterGlobalImports).join('\n');
                if (flutterPartDeclarations.size > 0) {
                    // FIXED: 使用实际的根模型名称来生成 part 文件名
                    finalFlutterCode += '\n' + `part '${actualRootModelName.toLowerCase()}.g.dart';`;
                }
                finalFlutterCode += '\n\n';

                sortedFlutterModelNames.forEach(name => {
                    finalFlutterCode += `// MARK: - ${name}.dart\n\n${generatedFlutterModels[name].content}\n\n`;
                });
                setFlutterCode(finalFlutterCode.trim());
            } else {
                setFlutterCode('');
            }


            setObjcHeader(finalObjcHeader.trim());
            setObjcImplementation(finalObjcImplementation.trim());
            setSwiftCode(finalSwiftCode.trim());

        } catch (e) {
            setError('JSON 输入无效。请检查您的 JSON 格式。');
            console.error('JSON 解析错误：', e);
        } finally {
            setIsLoading(false);
        }
    };

    // 使用 Gemini API 建议模型名称的功能
    const suggestModelName = async () => {
        if (!jsonInput) {
            setError('请先粘贴 JSON 数据以获取建议。');
            return;
        }
        setIsSuggestingName(true);
        setSuggestedModelName('');
        setError('');

        try {
            const chatHistory = [];
            const prompt = `给定以下 JSON 数据，最合适和最具描述性的根模型名称是什么？只提供建议的名称，不包含其他内容。JSON： \n\n\`\`\`json\n${jsonInput}\n\`\`\``;
            chatHistory.push({ role: "user", parts: [{ text: prompt }] });
            const payload = { contents: chatHistory };
            const apiUrl = `https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent?key=${apiKey}`;
            const response = await fetch(apiUrl, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(payload)
            });
            const result = await response.json();

            if (result.candidates && result.candidates.length > 0 &&
                result.candidates[0].content && result.candidates[0].content.parts &&
                result.candidates[0].content.parts.length > 0) {
                let suggested = result.candidates[0].content.parts[0].text.trim();
                // 清理常见的 LLM 响应格式
                suggested = suggested.replace(/^```[a-zA-Z]*\s*|\s*```$/g, ''); // 移除 markdown 代码块
                suggested = suggested.replace(/["'.]/g, ''); // 移除引号或句号
                // 将建议名称的首字母大写
                suggested = capitalizeFirstLetter(suggested);
                setSuggestedModelName(suggested);
                setModelName(suggested); // 可选：自动填充输入框
            } else {
                setSuggestedModelName('未能获取建议名称。');
            }
        } catch (e) {
            console.error("建议模型名称时出错：", e);
            setError('获取建议模型名称时出错。');
            setSuggestedModelName('未能获取建议名称。');
        } finally {
            setIsSuggestingName(false);
        }
    };

    // 使用 Gemini API 解释模型的功能
    const explainModel = async () => {
        if (!swiftCode) {
            setError('请先生成模型代码以获取解释。');
            return;
        }
        setIsExplainingModel(true);
        setModelExplanation('');
        setError('');

        try {
            const chatHistory = [];
            const prompt = `以简洁易懂的方式解释以下 Swift 数据模型的结构和目的。只提供解释，不包含代码或其他格式。Swift 模型：\n\n\`\`\`swift\n${swiftCode}\n\`\`\``;
            chatHistory.push({ role: "user", parts: [{ text: prompt }] });
            const payload = { contents: chatHistory };
            const apiUrl = `https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent?key=${apiKey}`;
            const response = await fetch(apiUrl, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(payload)
            });
            const result = await response.json();

            if (result.candidates && result.candidates.length > 0 &&
                result.candidates[0].content && result.candidates[0].content.parts &&
                result.candidates[0].content.parts.length > 0) {
                setModelExplanation(result.candidates[0].content.parts[0].text.trim());
            } else {
                setModelExplanation('未能获取模型解释。');
            }
        } catch (e) {
            console.error("解释模型时出错：", e);
            setError('获取模型解释时出错。');
            setModelExplanation('未能获取模型解释。');
        } finally {
            setIsExplainingModel(false);
        }
    };


    // 复制文本到剪贴板的功能
    const copyToClipboard = (ref) => {
        if (ref.current) {
            ref.current.select();
            document.execCommand('copy');
            // 注意: 在浏览器环境中，alert() 会阻塞主线程，影响用户体验。
            // 更好的做法是使用一个临时消息或 Toast 通知。
            alert('代码已复制到剪贴板！');
        }
    };

    return (
        <div className="min-h-screen bg-gray-100 flex flex-col items-center p-4 font-sans antialiased">
            {/* 样式通常放在单独的 CSS 文件中，或者在 HTML 的 <head> 部分 */}
            {/* <style> 标签及其内容已从 App.js 中移除，因为它更适合放在 HTML 文件中 */}
            
            {/* 主容器，白色背景，圆角，大阴影，全宽，最大宽度限制，底部外边距，边框 */}
            <div className="bg-white p-8 rounded-lg shadow-xl w-full max-w-7xl mb-8 border border-gray-200"> {/* 增加 max-w 以留出更多空间 */}
                {/* 标题 */}
                <h1 className="text-3xl font-bold text-center text-gray-800 mb-6">
                    JSON 数据模型生成器
                </h1>

                {/* 错误信息显示区域 */}
                {error && (
                    <div className="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded-md relative mb-6 border-dashed" role="alert">
                        <strong className="font-bold">错误:</strong>
                        <span className="block sm:inline"> {error}</span>
                    </div>
                )}

                {/* 主内容区域，采用 Flexbox 布局，在大屏幕上显示为三列 */}
                <div className="flex flex-col lg:flex-row gap-6"> {/* 适用于大屏幕的三列布局 */}
                    {/* 左侧列：JSON 输入区域 */}
                    <div className="flex-1 min-w-0 p-4 bg-gray-50 rounded-lg border border-gray-200">
                        <h2 className="text-xl font-bold text-gray-700 mb-4">JSON 数据输入区域</h2>
                        <label htmlFor="json-input" className="block text-gray-700 text-sm font-semibold mb-2">
                            粘贴你的 JSON 数据:
                        </label>
                        <textarea
                            id="json-input"
                            className="w-full p-4 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 transition duration-200"
                            rows="25" /* 调整行数以增加高度 */
                            placeholder='例如: {"id": 1, "name": "Test", "data": {"key": "value", "items": [{"id": 101}]}}'
                            value={jsonInput}
                            onChange={(e) => setJsonInput(e.target.value)}
                        ></textarea>
                    </div>

                    {/* 中间列：生成的代码区域和操作按钮 */}
                    <div className="flex-2 min-w-0 p-4 bg-gray-50 rounded-lg border border-gray-200 flex flex-col">
                        <h2 className="text-xl font-bold text-gray-700 mb-4">生成的代码区域</h2>

                        {/* 模型名称输入和 AI 建议按钮 */}
                        <div className="mb-4 flex flex-col sm:flex-row items-stretch sm:items-end gap-4">
                            <div className="flex-grow">
                                <label htmlFor="model-name" className="block text-gray-700 text-sm font-semibold mb-2">
                                    根模型名称:
                                </label>
                                <div className="flex items-center gap-2">
                                    <input
                                        type="text"
                                        id="model-name"
                                        className="flex-grow p-3 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 transition duration-200"
                                        value={modelName}
                                        onChange={(e) => setModelName(e.target.value)}
                                        placeholder="例如: User, Product"
                                    />
                                    <button
                                        onClick={suggestModelName}
                                        className="bg-purple-600 text-white font-bold py-3 px-4 rounded-md hover:bg-purple-700 transition duration-300 ease-in-out focus:outline-none focus:ring-2 focus:ring-purple-500 focus:ring-opacity-50 flex-shrink-0"
                                        disabled={isSuggestingName || !jsonInput}
                                    >
                                        {isSuggestingName ? '建议中...' : '✨ AI 建议名称'}
                                    </button>
                                </div>
                                {suggestedModelName && (
                                    <p className="text-sm text-gray-600 mt-2">
                                        AI 建议: <span className="font-semibold text-blue-700">{suggestedModelName}</span>
                                    </p>
                                )}
                            </div>
                        </div>

                        {/* 新增：类名前缀输入框 */}
                        <div className="mb-6">
                            <label htmlFor="class-prefix" className="block text-gray-700 text-sm font-semibold mb-2">
                                类名前缀 (可选):
                            </label>
                            <input
                                type="text"
                                id="class-prefix"
                                className="w-full p-3 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 transition duration-200"
                                value={classNamePrefix}
                                onChange={(e) => setClassNamePrefix(e.target.value)}
                                placeholder="例如: My, API"
                            />
                        </div>

                        {/* 生成模型按钮 */}
                        <button
                            onClick={generateModels}
                            className="w-full sm:w-auto bg-blue-600 text-white font-bold py-3 px-6 rounded-md hover:bg-blue-700 transition duration-300 ease-in-out focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-opacity-50 flex-shrink-0 mb-6"
                            disabled={isLoading}
                        >
                            {isLoading ? '生成中...' : '生成模型'}
                        </button>


                        {/* 输出区域：显示生成的代码 */}
                        {(objcHeader || objcImplementation || swiftCode || flutterCode) && (
                            <div className="flex-grow overflow-hidden"> {/* 使用 flex-grow 和 overflow-hidden 使子元素可滚动 */}
                                <div className="grid grid-cols-1 gap-6 h-full"> {/* 用于生成代码输出的内部网格 */}
                                    {/* Objective-C 头文件显示区域 */}
                                    {(selectedLanguage === 'objc' || selectedLanguage === 'both') && objcHeader && (
                                        <div className="flex flex-col">
                                            <h3 className="text-lg font-bold text-gray-700 mb-2 flex justify-between items-center">
                                                Objective-C (.h)
                                                <button
                                                    onClick={() => copyToClipboard(objcHeaderRef)}
                                                    className="bg-gray-200 text-gray-800 text-sm py-1.5 px-3.5 rounded-md hover:bg-gray-300 transition duration-200 shadow-sm"
                                                >
                                                    复制
                                                </button>
                                            </h3>
                                            <div className="bg-gray-900 text-green-400 p-4 rounded-md shadow-inner scrollable-code border border-gray-700 flex-grow">
                                                <textarea
                                                    ref={objcHeaderRef}
                                                    className="w-full h-full bg-transparent text-sm resize-none outline-none border-none font-mono"
                                                    value={objcHeader}
                                                    readOnly
                                                />
                                            </div>
                                        </div>
                                    )}

                                    {/* Objective-C 实现文件显示区域 */}
                                    {(selectedLanguage === 'objc' || selectedLanguage === 'both') && objcImplementation && (
                                        <div className="flex flex-col">
                                            <h3 className="text-lg font-bold text-gray-700 mb-2 flex justify-between items-center">
                                                Objective-C (.m)
                                                <button
                                                    onClick={() => copyToClipboard(objcImplementationRef)}
                                                    className="bg-gray-200 text-gray-800 text-sm py-1.5 px-3.5 rounded-md hover:bg-gray-300 transition duration-200 shadow-sm"
                                                >
                                                    复制
                                                </button>
                                            </h3>
                                            <div className="bg-gray-900 text-green-400 p-4 rounded-md shadow-inner scrollable-code border border-gray-700 flex-grow">
                                                <textarea
                                                    ref={objcImplementationRef}
                                                    className="w-full h-full bg-transparent text-sm resize-none outline-none border-none font-mono"
                                                    value={objcImplementation}
                                                    readOnly
                                                />
                                            </div>
                                        </div>
                                    )}

                                    {/* Swift 代码显示区域 */}
                                    {(selectedLanguage === 'swift' || selectedLanguage === 'both') && swiftCode && (
                                        <div className="flex flex-col">
                                            <h3 className="text-lg font-bold text-gray-700 mb-2 flex justify-between items-center">
                                                Swift (.swift)
                                                <button
                                                    onClick={() => copyToClipboard(swiftCodeRef)}
                                                    className="bg-gray-200 text-gray-800 text-sm py-1.5 px-3.5 rounded-md hover:bg-gray-300 transition duration-200 shadow-sm"
                                                >
                                                    复制
                                                </button>
                                            </h3>
                                            <div className="bg-gray-900 text-green-400 p-4 rounded-md shadow-inner scrollable-code border border-gray-700 flex-grow">
                                                <textarea
                                                    ref={swiftCodeRef}
                                                    className="w-full h-full bg-transparent text-sm resize-none outline-none border-none font-mono"
                                                    value={swiftCode}
                                                    readOnly
                                                />
                                            </div>
                                            {/* AI 解释模型按钮 */}
                                            <button
                                                onClick={explainModel}
                                                className="w-full mt-4 bg-green-600 text-white font-bold py-3 px-6 rounded-md hover:bg-green-700 transition duration-300 ease-in-out focus:outline-none focus:ring-2 focus:ring-green-500 focus:ring-opacity-50 shadow-md"
                                                disabled={isExplainingModel || !swiftCode}
                                            >
                                                {isExplainingModel ? '解释中...' : '✨ 解释模型'}
                                            </button>
                                            {/* 模型解释显示区域 */}
                                            {modelExplanation && (
                                                <div className="mt-4 p-4 bg-blue-100 border border-blue-400 text-blue-800 rounded-md border-dashed">
                                                    <strong className="font-bold">AI 模型解释:</strong>
                                                    <p className="mt-2 text-sm leading-relaxed">{modelExplanation}</p>
                                                </div>
                                            )}
                                        </div>
                                    )}

                                    {/* Flutter 代码显示区域 */}
                                    {(selectedLanguage === 'flutter' || selectedLanguage === 'both') && flutterCode && (
                                        <div className="flex flex-col">
                                            <h3 className="text-lg font-bold text-gray-700 mb-2 flex justify-between items-center">
                                                Flutter/Dart (.dart)
                                                <button
                                                    onClick={() => copyToClipboard(flutterCodeRef)}
                                                    className="bg-gray-200 text-gray-800 text-sm py-1.5 px-3.5 rounded-md hover:bg-gray-300 transition duration-200 shadow-sm"
                                                >
                                                    复制
                                                </button>
                                            </h3>
                                            <div className="bg-gray-900 text-blue-400 p-4 rounded-md shadow-inner scrollable-code border border-gray-700 flex-grow">
                                                <textarea
                                                    ref={flutterCodeRef}
                                                    className="w-full h-full bg-transparent text-sm resize-none outline-none border-none font-mono"
                                                    value={flutterCode}
                                                    readOnly
                                                />
                                            </div>
                                            {/* json_serializable 框架的注意事项 */}
                                            {(flutterFramework === 'JsonSerializable' && flutterCode) && (
                                                <div className="mt-4 p-4 bg-yellow-100 border border-yellow-400 text-yellow-800 rounded-md border-dashed">
                                                    <strong className="font-bold">注意:</strong>
                                                    <p className="mt-2 text-sm leading-relaxed">
                                                        使用 `json_serializable` 框架需要运行 `flutter pub run build_runner build` 命令来生成 `.g.dart` 文件。请确保在 `pubspec.yaml` 中添加了 `json_annotation`、`json_serializable` 和 `build_runner` 依赖项。
                                                    </p>
                                                </div>
                                            )}
                                        </div>
                                    )}
                                </div>
                            </div>
                        )}
                    </div>

                    {/* 右侧列：语言和第三方库选择区域 */}
                    <div className="flex-1 min-w-0 p-4 bg-gray-50 rounded-lg border border-gray-200">
                        <h2 className="text-xl font-bold text-gray-700 mb-4">语言和第三方库选择区域</h2>
                        <div className="mb-6">
                            <label className="block text-gray-700 text-sm font-semibold mb-2">
                                选择生成语言:
                            </label>
                            <div className="flex flex-col space-y-2 p-3 border border-gray-300 rounded-md bg-gray-50">
                                <label className="inline-flex items-center">
                                    <input
                                        type="radio"
                                        className="form-radio text-blue-600"
                                        name="language"
                                        value="both"
                                        checked={selectedLanguage === 'both'}
                                        onChange={(e) => setSelectedLanguage(e.target.value)}
                                    />
                                    <span className="ml-2 text-gray-700">全部</span>
                                </label>
                                <label className="inline-flex items-center">
                                    <input
                                        type="radio"
                                        className="form-radio text-blue-600"
                                        name="language"
                                        value="objc"
                                        checked={selectedLanguage === 'objc'}
                                        onChange={(e) => setSelectedLanguage(e.target.value)}
                                    />
                                    <span className="ml-2 text-gray-700">Objective-C</span>
                                </label>
                                <label className="inline-flex items-center">
                                    <input
                                        type="radio"
                                        className="form-radio text-blue-600"
                                        name="language"
                                        value="swift"
                                        checked={selectedLanguage === 'swift'}
                                        onChange={(e) => setSelectedLanguage(e.target.value)}
                                    />
                                    <span className="ml-2 text-gray-700">Swift</span>
                                </label>
                                <label className="inline-flex items-center">
                                    <input
                                        type="radio"
                                        className="form-radio text-blue-600"
                                        name="language"
                                        value="flutter"
                                        checked={selectedLanguage === 'flutter'}
                                        onChange={(e) => setSelectedLanguage(e.target.value)}
                                    />
                                    <span className="ml-2 text-gray-700">Flutter/Dart</span>
                                </label>
                            </div>
                        </div>

                        {/* Swift 框架选择 */}
                        {(selectedLanguage === 'swift' || selectedLanguage === 'both') && (
                            <div className="mb-6">
                                <label className="block text-gray-700 text-sm font-semibold mb-2">
                                    Swift 框架:
                                </label>
                                <div className="flex flex-col space-y-2 p-3 border border-gray-300 rounded-md bg-gray-50">
                                    <label className="inline-flex items-center">
                                        <input type="radio" className="form-radio text-green-600" name="swiftFramework" value="Codable" checked={swiftFramework === 'Codable'} onChange={(e) => setSwiftFramework(e.target.value)} />
                                        <span className="ml-2 text-gray-700">Codable</span>
                                    </label>
                                    <label className="inline-flex items-center">
                                        <input type="radio" className="form-radio text-green-600" name="swiftFramework" value="HandyJSON" checked={swiftFramework === 'HandyJSON'} onChange={(e) => setSwiftFramework(e.target.value)} />
                                        <span className="ml-2 text-gray-700">HandyJSON</span>
                                    </label>
                                    <label className="inline-flex items-center">
                                        <input type="radio" className="form-radio text-green-600" name="swiftFramework" value="SwiftyJSON" checked={swiftFramework === 'SwiftyJSON'} onChange={(e) => setSwiftFramework(e.target.value)} />
                                        <span className="ml-2 text-gray-700">SwiftyJSON</span>
                                    </label>
                                </div>
                            </div>
                        )}

                        {/* Objective-C 框架选择 */}
                        {(selectedLanguage === 'objc' || selectedLanguage === 'both') && (
                            <div className="mb-6">
                                <label className="block text-gray-700 text-sm font-semibold mb-2">
                                    Objective-C 框架:
                                </label>
                                <div className="flex flex-col space-y-2 p-3 border border-gray-300 rounded-md bg-gray-50">
                                    <label className="inline-flex items-center">
                                        <input type="radio" className="form-radio text-red-600" name="objcFramework" value="System" checked={objcFramework === 'System'} onChange={(e) => setObjcFramework(e.target.value)} />
                                        <span className="ml-2 text-gray-700">系统生成</span>
                                    </label>
                                    <label className="inline-flex items-center">
                                        <input type="radio" className="form-radio text-red-600" name="objcFramework" value="MJExtension" checked={objcFramework === 'MJExtension'} onChange={(e) => setObjcFramework(e.target.value)} />
                                        <span className="ml-2 text-gray-700">MJExtension</span>
                                    </label>
                                    <label className="inline-flex items-center">
                                        <input type="radio" className="form-radio text-red-600" name="objcFramework" value="YYModel" checked={objcFramework === 'YYModel'} onChange={(e) => setObjcFramework(e.target.value)} />
                                        <span className="ml-2 text-gray-700">YYModel</span>
                                    </label>
                                </div>
                            </div>
                        )}

                        {/* Flutter 框架选择 */}
                        {(selectedLanguage === 'flutter' || selectedLanguage === 'both') && (
                            <div className="mb-6">
                                <label className="block text-gray-700 text-sm font-semibold mb-2">
                                    Flutter/Dart 框架:
                                </label>
                                <div className="flex flex-col space-y-2 p-3 border border-gray-300 rounded-md bg-gray-50">
                                    <label className="inline-flex items-center">
                                        <input type="radio" className="form-radio text-indigo-600" name="flutterFramework" value="System" checked={flutterFramework === 'System'} onChange={(e) => setFlutterFramework(e.target.value)} />
                                        <span className="ml-2 text-gray-700">系统生成</span>
                                    </label>
                                    <label className="inline-flex items-center">
                                        <input type="radio" className="form-radio text-indigo-600" name="flutterFramework" value="JsonSerializable" checked={flutterFramework === 'JsonSerializable'} onChange={(e) => setFlutterFramework(e.target.value)} />
                                        <span className="ml-2 text-gray-700">json_serializable</span>
                                    </label>
                                </div>
                            </div>
                        )}
                    </div>
                </div>
            </div>
        </div>
    );
};

export default App;
